class Question < ActiveRecord::Base

  belongs_to :grouping

  has_many :options, :class_name => 'QuestionOption'
  has_many :texts, :class_name => 'QuestionByRole'

  validates_inclusion_of :kind, :in => ['yes_no', 'text', 'option', 'excluding']

  # Given a role, returns the by role view of the question
  def for_role(role_or_kind)
    role_or_kind = role_or_kind.kind if role_or_kind.respond_to? :kind
    self.texts.find_by_kind role_or_kind.to_s
  end
  
  # Given a role, returns the text to display for the question
  def text_for(role_or_kind)
    self.for_role(role_or_kind).text
  rescue
    nil
  end

  def is_yes_no
    self.kind == 'yes_no'
  end

  def is_text
    self.kind == 'text'
  end
  
  def is_option
    self.kind == 'option'
  end
  
  def is_excluding
    self.kind == 'excluding'
  end
  
  def yes_clarification
    self.options.find_by_code('YES') if self.is_yes_no
  end
  
  def no_clarification
    self.options.find_by_code('NO') if self.is_yes_no
  end
  
  def yes_xb_clarification
    self.options.find_by_code('YES_XB') if self.is_yes_no
  end
  
  def no_xb_clarification
    self.options.find_by_code('NO_XB') if self.is_yes_no
  end
  
  # Indicates if the question should be answered by the given role
  def available_for(role)
    question_by_role = self.for_role(role)
    not question_by_role.nil? and not question_by_role.first_column_auto?
  end

end
